/**
 * 仓库 - 新增或编辑界面
 * 
 * @author 艾格林门信息服务（大连）有限公司
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Warehouse.EditForm", {
  extend: "PSI.AFX.Form.EditForm",

  /**
   * 初始化组件
   * 
   * @override
   */
  initComponent() {
    const me = this;

    const entity = me.getEntity();

    me.adding = entity == null;

    const buttons = [];
    if (!entity) {
      const btn = {
        text: "保存并继续新建",
        formBind: true,
        handler() {
          me.onOK(true);
        },
        scope: me
      };

      buttons.push(btn);
    }

    let btn = {
      text: "保存",
      formBind: true,
      iconCls: "PSI-button-ok",
      handler() {
        me.onOK(false);
      },
      scope: me
    };
    buttons.push(btn);

    btn = {
      text: entity == null ? "关闭" : "取消",
      handler() {
        me.close();
      },
      scope: me
    };
    buttons.push(btn);

    const t = entity == null ? "新建仓库" : "编辑仓库";
    const logoHtml = me.genLogoHtml(entity, t);

    const listeners = {
      specialkey: {
        fn: me.__onEditSpecialKey,
        scope: me
      }
    };

    const C = {
      editForm: me.buildId(me, "editForm"),
      editCode: me.buildId(me, "editCode"),
      editName: me.buildId(me, "editName"),
      editOrg: me.buildId(me, "editOrg"),
      hiddenOrgId: me.buildId(me, "hiddenOrgId"),
      editSaleArea: me.buildId(me, "editSaleArea"),
      editEnabled: me.buildId(me, "editEnabled"),
      hiddenEnabled: me.buildId(me, "hiddenEnabled"),
      editUsageType: me.buildId(me, "editUsageType"),
      hiddenUsageType: me.buildId(me, "hiddenUsageType"),
      editLimitGoods: me.buildId(me, "editLimitGoods"),
    };

    PCL.apply(me, {
      header: {
        title: me.formatTitle(PSI.Const.PROD_NAME),
        height: 40
      },
      width: 800,
      height: 360,
      layout: "border",
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
        close: {
          fn: me._onWndClose,
          scope: me
        }
      },
      items: [{
        region: "north",
        height: 70,
        border: 0,
        html: logoHtml
      }, {
        region: "center",
        border: 0,
        id: C.editForm,
        xtype: "form",
        layout: {
          type: "table",
          columns: 2,
          tableAttrs: PSI.Const.TABLE_LAYOUT,
        },
        height: "100%",
        bodyPadding: 5,
        defaultType: 'textfield',
        fieldDefaults: {
          labelWidth: 80,
          labelAlign: "right",
          labelSeparator: "",
          msgTarget: 'side',
          width: 370,
          margin: "5"
        },
        items: [{
          xtype: "hidden",
          name: "id",
          value: entity == null ? null : entity.get("id")
        }, {
          id: C.editCode,
          fieldLabel: "仓库编码",
          allowBlank: false,
          blankText: "没有输入仓库编码",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          name: "code",
          value: entity == null ? null : entity.get("code"),
          listeners,
        }, {
          id: C.editName,
          fieldLabel: "仓库名称",
          allowBlank: false,
          blankText: "没有输入仓库名称",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          name: "name",
          value: entity == null ? null : entity.get("name"),
          listeners,
        }, {
          id: C.editOrg,
          fieldLabel: "核算组织机构",
          xtype: "psi_orgfield",
          value: entity == null ? null : entity.get("orgName"),
          listeners,
        }, {
          id: C.hiddenOrgId,
          xtype: "hidden",
          name: "orgId"
        }, {
          id: C.editSaleArea,
          fieldLabel: "销售核算面积",
          value: entity == null ? null : entity.get("saleArea"),
          xtype: "numberfield",
          hideTrigger: true,
          allowDecimal: true,
          minValue: 0,
          name: "saleArea",
          listeners,
        }, {
          id: C.editEnabled,
          xtype: "combo",
          queryMode: "local",
          editable: false,
          valueField: "id",
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "状态",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [[1, "启用"], [2, "停用"]]
          }),
          value: entity == null
            ? 1
            : parseInt(entity.get("enabled")),
          listeners,
        }, {
          id: C.hiddenEnabled,
          xtype: "hidden",
          name: "enabled"
        }, {
          id: C.editUsageType,
          xtype: "combo",
          queryMode: "local",
          editable: false,
          valueField: "id",
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "用途",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [[10, "原材料库"], [20, "半成品库"], [30, "产成品库"], [40, "商品库"]]
          }),
          value: entity == null
            ? 40
            : parseInt(entity.get("usageType")),
          listeners,
        }, {
          id: C.hiddenUsageType,
          xtype: "hidden",
          name: "usageType"
        }, {
          id: C.editLimitGoods,
          xtype: "combo",
          queryMode: "local",
          editable: false,
          valueField: "id",
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "物料限制",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [[0, "不启用物料限制"], [1, "启用物料限制"]]
          }),
          value: entity == null
            ? 1
            : parseInt(entity.get("limitGoods")),
          name: "limitGoods",
          listeners: {
            specialkey: {
              fn: me._onLastEditSpecialKey,
              scope: me
            }
          }
        }],
        buttons: buttons
      }]
    });

    me.callParent(arguments);

    me.editForm = PCL.getCmp(C.editForm);

    me.editCode = PCL.getCmp(C.editCode);
    me.editName = PCL.getCmp(C.editName);
    me.editEnabled = PCL.getCmp(C.editEnabled);
    me.editOrg = PCL.getCmp(C.editOrg);
    me.editSaleArea = PCL.getCmp(C.editSaleArea);
    me.hiddenEnabled = PCL.getCmp(C.hiddenEnabled);
    me.hiddenOrgId = PCL.getCmp(C.hiddenOrgId);
    me.editUsageType = PCL.getCmp(C.editUsageType);
    me.hiddenUsageType = PCL.getCmp(C.hiddenUsageType);
    me.editLimitGoods = PCL.getCmp(C.editLimitGoods);

    if (!me.adding) {
      me.editOrg.setIdValue(entity.get("orgId"));
    }

    me.__editorList = [me.editCode, me.editName, me.editOrg, me.editSaleArea, me.editEnabled,
    me.editUsageType, me.editLimitGoods];
  },

  /**
   * 保存
   * 
   * @private
   */
  onOK(thenAdd) {
    const me = this;

    me.hiddenOrgId.setValue(me.editOrg.getIdValue());
    me.hiddenEnabled.setValue(me.editEnabled.getValue());
    me.hiddenUsageType.setValue(me.editUsageType.getValue());

    const f = me.editForm;
    const el = f.getEl();
    el.mask(PSI.Const.SAVING);
    const sf = {
      url: me.URL("SLN0001/Warehouse/editWarehouse"),
      method: "POST",
      success(form, action) {
        me._lastId = action.result.id;

        el.unmask();

        me.tip("数据保存成功", !thenAdd);
        me.focus();
        if (thenAdd) {
          me.clearEdit();
        } else {
          me.close();
        }
      },
      failure(form, action) {
        el.unmask();
        me.showInfo(action.result.msg, () => {
          me.editCode.focus();
        });
      }
    };
    f.submit(sf);
  },

  /**
   * @private
   */
  _onLastEditSpecialKey(field, e) {
    var me = this;

    if (e.getKey() == e.ENTER) {
      var f = me.editForm;
      if (f.getForm().isValid()) {
        me.onOK(me.adding);
      }
    }
  },

  /**
   * @private
   */
  clearEdit() {
    const me = this;
    me.editCode.focus();

    const editors = [me.editCode, me.editName];
    for (let i = 0; i < editors.length; i++) {
      const edit = editors[i];
      edit.setValue(null);
      edit.clearInvalid();
    }
  },

  /**
   * @private
   */
  _onWndClose() {
    const me = this;

    PCL.get(window).un('beforeunload', me.__onWindowBeforeUnload);

    if (me._lastId) {
      const parentForm = me.getParentForm();
      if (parentForm) {
        parentForm.refreshGrid.apply(parentForm, [me._lastId]);
      }
    }
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    PCL.get(window).on('beforeunload', me.__onWindowBeforeUnload);

    me.setFocusAndCursorPosToLast(me.editCode);
  }
});
